<template>
  <div v-loading="loading" class="dashboard-container">
    <div class="app-container">
      <el-card class="tree-card">
        <tree-tools
          :tree-node="company"
          :is-root="true"
          class="header"
          @addDep="addDepFn"
        />
        <el-tree :data="depts" :props="defaultProps" default-expand-all>
          <template v-slot="{ data }">
            <tree-tools
              :tree-node="data"
              class="main"
              :update-deps="getDepartment"
              @addDep="addDepFn"
              @editDep="editDepFn"
            />
          </template>
        </el-tree>
      </el-card>
    </div>
    <Add
      ref="addDep"
      :visible.sync="addVisible"
      :current-node="currentNode"
      :origin-depts="originDepts"
      @updateDeps="updateDeps"
    />
  </div>
</template>

<script>
import { getDepartment } from '@/api/department'
import TreeTools from './components/TreeTools.vue'
import Add from './components/Add.vue'
import { tranListToTreeData } from '@/utils'
export default {
  components: { TreeTools, Add },
  data() {
    return {
      defaultProps: {
        label: 'name'
      },
      company: {
        name: '传智教育'
      },
      depts: [],
      addVisible: false,
      currentNode: {},
      originDepts: [],
      loading: false
    }
  },

  created() {
    this.getDepartment()
  },
  methods: {
    handleNodeClick(data) {
      console.log(data)
    },
    async getDepartment() {
      try {
        this.loading = true
        const res = await getDepartment()
        console.log(res)
        this.originDepts = res.depts
        this.depts = tranListToTreeData(res.depts, '')
        this.company = {
          name: res.companyName,
          manager: '负责人',
          children: this.depts
        }
      } finally {
        this.loading = false
      }
    },
    addDepFn(currentNode) {
      console.log('王行你在狗叫什么')
      this.addVisible = true
      this.currentNode = currentNode
    },
    updateDeps() {
      this.getDepartment()
    },
    editDepFn(node) {
      console.log(node)
      this.addVisible = true
      this.$refs.addDep.formData = { ...node, children: '' }
    }
  }
}
</script>

<style scoped>
.tree-card {
  padding: 30px 60px;
  font-size: 14px;
}
.header {
  height: 30px;
}
.main {
  height: 25px;
  line-height: 25px;
}
</style>
